﻿var url = "Handlers/UsersManagerHandler.ashx";
$(function () {
    var r = Math.random();
    $.post(url + "?" + r, function (jsonData) {
        loadData(jsonData)
    }, "json");
});
//获取用户信息并生成表格数据
function loadData(data) {
    var r = Math.random();
    //查询角色数据
    $.post(url+"?"+r, { rl: 0 }, function (jsonData) {
        $("tbody").empty();
        //生成表格数据
        for (var i = 0; i < data.length;i++) {
            var user = data[i];
            var $tr = $("<tr></tr>");
            $tr.append("<td>" + user.UserId + "</td>");
            $tr.append("<td>" + user.LoginId + "</td>");
            $tr.append("<td>" + user.UserName + "</td>");
            $tr.append("<td>" + user.Phone + "</td>");
            $tr.append("<td>" + user.UserStatus + "</td>");
            $tr.append("<td>" + user.DateCreated + "</td>");
            //生成角色信息下拉列表框
            var $rolesTd = $("<td></td>");
            var $roles = $("<select id='ddlRoles" + user.UserId+"'></select>");
            for (var j = 0; j < jsonData.length; j++) {
                var role = jsonData[j];
                if (role.RoleId == user.RoleId) {
                    $roles.append("<option value='" + role.RoleId + "' selected='true'>" + role.Name + "</option>");
                } else {
                    $roles.append("<option value='" + role.RoleId + "'>" + role.Name + "</option>");
                }
            }
            $rolesTd.append($roles);
            $rolesTd.append("<input type='button' class='button-default pure-button pure-button-primary' onclick='btnChange_click(\"#ddlRoles" + user.UserId + "\"," + user.UserId + ")' value='更改' />");
            $tr.append($rolesTd);  
            if (user.RoleId != 1) {
                $tr.append("<td><input type='button' class='button-default pure-button tools-button' onclick='btnRemove_click(this," + user.UserId + ")' value='禁用' /></td>");
            }
            else {
                $tr.append("<td> - </td>");
            }     
                     
            $("tbody").append($tr);
        }
    }, "json");
} 
//更改用户角色
function btnChange_click(ddl, userId) {
    var roleId =$(ddl).val();
    var r = Math.random();
    $.post(url + "?" + r, { uid: userId,rid:roleId }, function (jsonData) {
        loadData(jsonData)
    }, "json");
}
//启用或禁用用户
function btnRemove_click(btn, userId) {
    var r = Math.random();
    var lbl = ($(btn).val() === "禁用" ? "启用" : "禁用");
    $(btn).val(lbl);
    $.post(url + "?" + r, { uid: userId }, function (jsonData) {
        loadData(jsonData)
    }, "json");
}